#include "stdafx.h"
#include "VS2010CtxMenuFixHook.h"

static TCHAR g_szRegSubKey[] = __TEXT("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7");
static TCHAR g_szRegValueName[] = __TEXT("10.0");
static TCHAR g_szVsFileName[] = __TEXT("Common7\\IDE\\devenv.exe");

static BOOL GetVsInstallDir(LPTSTR, DWORD);
static BOOL GetCurrentProcessFileName(LPTSTR, DWORD);

BOOL GetIsVsProcess()
{
    TCHAR szVsInstallDir[MAX_PATH + 1];
    TCHAR szVsFileName[MAX_PATH + 1];
    TCHAR szProcessFileName[MAX_PATH + 1];

    if (!GetVsInstallDir(szVsInstallDir, MAX_PATH + 1))
    {
        return FALSE;
    }

    if (lstrlen(szVsInstallDir) + lstrlen(g_szVsFileName) > MAX_PATH)
    {
        return FALSE;
    }

    lstrcpy(szVsFileName, szVsInstallDir);
    lstrcat(szVsFileName, g_szVsFileName);

    if (!GetCurrentProcessFileName(szProcessFileName, MAX_PATH + 1))
    {
        return FALSE;
    }

    return lstrcmpi(szVsFileName, szProcessFileName) == 0;
}

static BOOL GetVsInstallDir(LPTSTR lpBuffer, DWORD nSize)
{
    DWORD cbData;

    cbData = sizeof(TCHAR) * nSize;
    if (RegGetValue(HKEY_CURRENT_USER, g_szRegSubKey, g_szRegValueName, RRF_RT_REG_SZ, NULL, (LPBYTE)lpBuffer, &cbData) == ERROR_SUCCESS)
    {
        return TRUE;
    }

    cbData = sizeof(TCHAR) * nSize;
    if (RegGetValue(HKEY_LOCAL_MACHINE, g_szRegSubKey, g_szRegValueName, RRF_RT_REG_SZ, NULL, (LPBYTE)lpBuffer, &cbData) == ERROR_SUCCESS)
    {
        return TRUE;
    }

    return FALSE;
}

static BOOL GetCurrentProcessFileName(LPTSTR lpBuffer, DWORD nSize)
{
    HANDLE hProcess = GetCurrentProcess();

    if (!GetModuleFileNameEx(hProcess, NULL, lpBuffer, nSize))
    {
        return FALSE;
    }

    return TRUE;
}
